package org.brisling.procurement.queryService;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.util.JsonUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.StringUtil;
import org.brisling.common.util.WhereUtil;

import org.brisling.ethic.domain.VOEthicEvaluateSub;
import org.brisling.procurement.domain.ProcurementDirect;
import org.brisling.procurement.domain.VOProcurementCount;
import org.brisling.procurement.domain.VOProcurementFlowCount;
import org.brisling.sysman.domain.Permissions;
import org.brisling.sysman.domain.Users;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryProcurementDirectService</p>
 * <p>Description: 采购管理直采项目查询服务类</p>
 * <p>Company: 长沙东勤信息科技发展有限公司</p>
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2018年11月9日 上午10:17:41
 */
@RestController
@RequestMapping("/procurementDirect/query")
public class QueryProcurementDirectService extends AbstractBaseQueryService<ProcurementDirect>{
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@Autowired
	private PermissionService permissionService;
	
	private String bizcode = "procurement";
	
	public QueryProcurementDirectService(){
		this.moduleName = ConstSysParam.MODULE_PROCUREMENT_DIRECT;
		this.subSystem = ConstSysParam.SUBSYSTEM_PROCUREMENT;
		this.tableName = this.moduleName;
		this.clazz = ProcurementDirect.class;
		typeMap = this.getTypeMap(clazz);
		
		
		orderMap.put("sortedid","");			
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return super.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return super.getBizEditPage();
	}
	
	@RequestMapping("/getPage.action")
	public ModelAndView getPage(@RequestParam(value="code",required=false) String code){
		
		String _code = code==null?"main":code;
		return new ModelAndView("/"+ConstSysParam.SUBSYSTEM_PROCUREMENT+"/"+_code);
	}	
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<ProcurementDirect> getListDomain(@RequestBody(required=false) String body){		
		
		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap, true);
		
	}
	
	/*
	 * 获取指定类型的采购计划数据集合
	 * @param body			前端传入的查询参数
	 * @param pur_typeid	采购计划类型（小型-1、中型-2、大型-3）
	 * @return
	 */
	private ListDomain<ProcurementDirect> getScaleDomain(String body,String pur_typeid,LinkedHashMap<String,String> oMap){		
		
		
		Map<String,Object> conditionMap = this.getBodyParam(body);
		Map<String,String> param_map = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		param_map =param_map == null?new HashMap<String,String>():param_map;
		param_map.put("pur_typeid", pur_typeid);
//		param_map.put("pur_typename","小型");
		
		conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, param_map);
		
		if( (oMap==null) || oMap.isEmpty() ){
			oMap = new LinkedHashMap<String,String>();
			oMap.put("createtime", "desc");
		}
		
		return super.getListDomainByConditionAndOrder(null, conditionMap, typeMap, oMap, true);	
		
	}
	
	/**
	 * 日常资产采购项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAssetLittleListDomain.action")
	public ListDomain<ProcurementDirect> getAssetLittleListDomain(@RequestBody(required=false) String body){		
		
		return this.getDirectListDomain(body, "1","procurementAssetSmall",null);	
		
	}
	/**
	 * 小型资产采购项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAssetSmallListDomain.action")
	public ListDomain<ProcurementDirect> getAssetSmallListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "1","procurementAssetSmall",null);
		return this.getDirectListDomain(body, "2","procurementAssetSmall",null);	
		
	}
	
	/**
	 * 中型资产项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAssetMiddleListDomain.action")
	public ListDomain<ProcurementDirect> getAssetMiddleListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "2","procurementAssetMiddle",null);	
		return this.getDirectListDomain(body, "3","procurementAssetMiddle",null);
		
		
	}
	
	/**
	 * 大型资产项目查询（自主招标）
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAssetBigListDomain.action")
	public ListDomain<ProcurementDirect> getAssetBigListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "3","procurementAssetBig",null);
		return this.getDirectListDomain(body, "4","procurementAssetBig",null);
				
	}
	
	/**
	 * 超大型资产采购项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getAssetLargeListDomain.action")
	public ListDomain<ProcurementDirect> getAssetLargeListDomain(@RequestBody(required=false) String body){		
		
		return this.getDirectListDomain(body, "5","procurementAssetLarge",null);	
		
	}
	
	/**
	 * 小型物资项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getMaterialSmallListDomain.action")
	public ListDomain<ProcurementDirect> getMaterialSmallListDomain(@RequestBody(required=false) String body){		
		
		
//		return this.getDirectListDomain(body, "4","procurementMaterialSmall",null);
		return this.getDirectListDomain(body, "11","procurementMaterialSmall",null);
		
		
	}
	
	/**
	 * 中型物资项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getMaterialMiddleListDomain.action")
	public ListDomain<ProcurementDirect> getMaterialMiddleListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "5","procurementMaterialMiddle",null);
		return this.getDirectListDomain(body, "12","procurementMaterialMiddle",null);
		
	}
	
	/**
	 * 大型物资项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getMaterialBigListDomain.action")
	public ListDomain<ProcurementDirect> getMaterialBigListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "6","procurementMaterialBig",null);
		return this.getDirectListDomain(body, "13","procurementMaterialBig",null);
				
	}
	
	/**
	 * 超大型物资项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getMaterialLargeListDomain.action")
	public ListDomain<ProcurementDirect> getMaterialLargeListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "6","procurementMaterialBig",null);
		return this.getDirectListDomain(body, "14","procurementMaterialLarge",null);
				
	}
	
	
	/**
	 * 物资配送项目查询
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDistributionListDomain.action")
	public ListDomain<ProcurementDirect> getDistributionListDomain(@RequestBody(required=false) String body){		
		
//		return this.getDirectListDomain(body, "7","procurementDistrubution",null);
		return this.getDirectListDomain(body, "21","procurementDistrubution",null);	
				
	}
	
	
	
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getInitListDomain.action")
	public ListDomain<Object> getInitListDomain(){		
		
		ListDomain<Object> domain= new ListDomain<Object>();
		String sql = String.format("select * from %1$s order by sortedid", this.tableName);
		List<LinkedHashMap> lists = super.getMappedList(sql);
		if(lists!=null && lists.size()>0){
			List<Object>  objs= super.reflectObjectMaps(VOEthicEvaluateSub.class, lists);
			domain.setRows(objs);
			domain.setTotal(new Long( objs.size()));
		}
		return domain;
		
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/getList.action")
	public List<ProcurementDirect> getList(@RequestBody(required=false) String body){		
		String sql = "";
		String whereCorse = null;					
		Map<String,Object> map = this.getBodyParam(body);
		
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		whereCorse = WhereUtil.getConditionWhereCorse(paramMap,typeMap);
		System.out.println("whereCorse: " +whereCorse);		
		
		if(whereCorse!=null && whereCorse.trim().length()>0){			
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		return super.getAllList(sql);
	}
	
	
	public List<ProcurementDirect> getListAll(Map<String, String> map){	
		
		String sql = "";
		String whereCorse = null;					
			
		whereCorse = WhereUtil.getConditionWhereCorse(map,typeMap);
		System.out.println("whereCorse: " +whereCorse);		
		
		if(whereCorse!=null && whereCorse.trim().length()>0){			
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		return super.getAllList(sql);
		
	}
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public ProcurementDirect getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public ProcurementDirect getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}	
	
	
	@RequestMapping("/getListByField.action")
	public List<ProcurementDirect> getListByField(@RequestParam(value="field",required=false) String field,@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return super.getListByIdentify(field,fieldVal);
	}
	
	
	@Autowired
	protected QueryDictionaryService dicService;
	
	/**
	 * 获取待处理及可查看采购计划数量，待处理计划状态标志位1，可查看计划状态标志位2
	 * @param body			参数变量
	 * @param userid		用户id
	 * @param pur_typeid	采购业务类型id
	 * @param fullBizcode	采购业务完整编码
	 * @return
	 */
	
	private ListDomain<ProcurementDirect> getDirectListDomain(
			String body,String pur_typeid,String bizcode,String userid
			){	
		
		if(userid == null){
			userid = shiroSecurityService.getCurrentUserIdentify();
		}
		
		String sql = dicService.getSqlByBizcode("procurement_query_list");
		
		Map<String,Object> conditionMap = this.getBodyParam(body);
		if(sql!=null){
			Map<String,Object> map = new HashMap<String,Object>();
			
			//添加用户可操作采购计划查询条件
			map.put("userid", userid);
			map.put("pur_typeid", pur_typeid);
			
			map.put("complete_status", "0");
			
			//添加用户可查看采购计划查询条件
			boolean  imd = this.isBizManaged(userid, bizcode);
			if(!imd){
				if(this.isManageJob(userid)){
					map.put("query_userid", userid);
				}else{
					String deptids = this.getUserDeptids(userid);
					map.put("query_deptid", deptids);
				}
				
			}
			sql = StringUtil.formatSql(sql, map);
			Integer[] pageParam = LongUtil.getPageParam(conditionMap);
			return getPagedListDomain(pageParam[0],pageParam[1],sql);		
		}
		return null;
	}
	
	/**
	 * 获取待处理计划数量
	 * @param userid	用户id
	 * @return
	 */
	@RequestMapping("/getPlanCount.action")
	public VOProcurementCount getPlanCount(@RequestParam(value="userid",required=false) String userid){	
		
		if(userid == null){
			userid = shiroSecurityService.getCurrentUserIdentify();
		}
		
		String sql = dicService.getSqlByBizcode("procurement_query_count");
		if(sql!=null){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userid", userid);
			
			//按照用户
			//添加用户可查看采购计划查询条件
			//添加用户可查看采购计划查询条件
			boolean  imd = this.isBizManaged(userid, bizcode);
			if(!imd){
				if(this.isManageJob(userid)){
					map.put("query_userid", userid);
				}else{
					String deptids = this.getUserDeptids(userid);
					map.put("query_deptid", deptids);
				}
				
			}
			sql = StringUtil.formatSql(sql, map);
			return super.getOneBySql(sql, VOProcurementCount.class);			
		}
		return null;
	}
	
	/**
	 * 获取单个计划业务待处理流程数量
	 * @param userid	用户id
	 * @param plan_id	计划id
	 * @return
	 */
	@RequestMapping("/getFlowCount.action")
	public VOProcurementFlowCount getFlowCount(@RequestParam(value="userid",required=false) String userid,
			@RequestParam(value="plan_id",required=false) String plan_id){	
		
		if(userid == null){
			userid = shiroSecurityService.getCurrentUserIdentify();
		}
		
		String sql = dicService.getSqlByBizcode("procurement_flow_count");
		if(sql!=null){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userid", userid);
			map.put("plan_id", plan_id);
			sql = StringUtil.formatSql(sql, map);
			return super.getOneBySql(sql, VOProcurementFlowCount.class);			
		}
		return null;
	}
	
	/**
	 * 根据bizcode获取fullbizcode
	 * @param conditionMap
	 * @return
	 */
	private String getFullBizcode(String bizcode){
		
		String fullBizcode = null;
		
		if(SysConfig.getFlowBizcodeMap()!=null){
			Permissions p =  SysConfig.getFlowBizcodeMap().get(bizcode);
			if (p!=null && p.getFullBizcode()!=null){
				fullBizcode= p.getFullBizcode();
			}
		}
			
		
		return fullBizcode;
		
	}
	
	private boolean isBizManaged(String userid,String bizcode){
		
		boolean ret = false;
		//参数有效性判断
		if(userid ==null || bizcode ==null){
			return false;
		}
		
		//获取用户信息
		Users usr = SysConfig.getUsr(userid);
		
		String userDeptid = usr.getDeptid().toString();		
		
		Permissions p = permissionService.getByBizcode(bizcode);
		if((null != p) && (p.getAddition_param()!=null)){
					//获取模块附加参数
			String param = p.getAddition_param().trim();
			Map<String,String> paramMap =JsonUtil.bodyToObj(param, HashMap.class);
			
			//获取模块管理部门id
			if((paramMap != null)&&(paramMap.containsKey(ConstSysParam.BIZ_MANAGE_DEPT))){
				String deptids = paramMap.get(ConstSysParam.BIZ_MANAGE_DEPT);
				
				//循环迭代判断用户部门id是否与模块业务管理部门id相同
				if(deptids!=null){
					String[] idArray = deptids.split(",");
					for(String _id:idArray){
						if(_id!=null){
							_id = _id.trim();
							if(userDeptid.compareTo(_id)==0){
								ret = true;
								break;
							}
						}
					}
				}
			}
		}
			
		return ret;
	}
}
